package com.example.test2.broadcast;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.example.test2.App;
import com.example.test2.utils.ToastUtils;

public class NetworkStateReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
            ConnectivityManager manager =
                    (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = manager.getActiveNetworkInfo();
            int type = -1;
            if (networkInfo != null && networkInfo.isAvailable()) {
                type = networkInfo.getType();
                onNetworkChange(type);
            } else {
                onNetworkChange(-1);
            }
        }
    }

    public void onNetworkChange(int type) {
        switch (type) {
            case ConnectivityManager.TYPE_WIFI:
                ToastUtils.getInstance().show(App.getContext(), "当前正在使用WLAN!");
                break;
            case ConnectivityManager.TYPE_MOBILE:
                ToastUtils.getInstance().show(App.getContext(), "当前正在使用移动网络,请注意流量消耗!");
                break;
            default:
                ToastUtils.getInstance().show(App.getContext(), "没有可用的网络连接！");
                break;
        }
    }
}
